package cn.com.longfuinfo.wx.controller;


import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.jfinal.aop.Duang;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Logger;
import com.jfinal.weixin.sdk.api.OrderExpireApi;
import com.jfinal.weixin.sdk.api.OrderRefundApi;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;

import cn.com.longfuinfo.wx.common.OrderCode;
import cn.com.longfuinfo.wx.dao.Goods;
import cn.com.longfuinfo.wx.dao.Order;
import cn.com.longfuinfo.wx.dao.OrderRefund;
import cn.com.longfuinfo.wx.dao.OrderRefundAPIRecord;
import cn.com.longfuinfo.wx.dao.User;
import cn.com.longfuinfo.wx.dao.UserMess;
import cn.com.longfuinfo.wx.dao.UserMoney;
import cn.com.longfuinfo.wx.dao.UserValueLog;

import cn.com.longfuinfo.wx.exception.SaveException;
import cn.com.longfuinfo.wx.kit.CommonKit;
import cn.com.longfuinfo.wx.kit.DatetimeKit;
import cn.com.longfuinfo.wx.kit.DoubleKit;
import cn.com.longfuinfo.wx.service.GoodsService;
import cn.com.longfuinfo.wx.service.OrderService;
import cn.com.longfuinfo.wx.service.UserService;

public class SynchronizationDate implements Runnable {

	private static Logger log = Logger.getLogger(SynchronizationDate.class);
	private static OrderService orderService= Duang.duang(OrderService.class);
	private UserService userservice = Duang.duang(UserService.class);
	private GoodsService goodsService =Duang.duang(GoodsService.class);;
	  
	@Override
	public void run() {
		 
		 try {
			   //在这里写你要执行的内容
				String times=  DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
				  //未支付订单过期
			    List<Order> list=orderService.findOrderList(times);
			    if(list.size()>0){
			    	
			    	for (Order order : list) {
			    		log.error("-------------未支付订单过期--------------"+list.size());
			    		//删除订单
			    		order.set("delState", OrderCode.DelState.YES);
			    		order.update();
			    		//发送消息
			    		UserMess usermess=new UserMess();
			    		usermess.set("userid", order.get("userid"))
			    		.set("from", order.get("orderNum"))
			    		.set("title", "订单已过期")
			    		.set("des", "您好，您的订单号为:"+order.get("orderNum")+"的订单，未在有效期支付"
			    				+ "OK妈咪已为您自动取消。")
			    		.set("state", 1).set("type", 1)
			    		.set("createDate",times)
			    		.save();
			    	}
			    }
			    //未兑换订单过期
			    List<Order> lists=orderService.findOrderLists(times);
			    if(lists.size()>0){
			    	
			    	for (Order order : lists) {
			    		log.error("-------------未兑换订单过期--------------"+lists.size());
			    		//修改订单状态过期
			    		order.set("orderState", OrderCode.OrderState.EXPIRE).set("tuistate",OrderCode.RefundState.VERIFYING ).update();
			    		//发送消息
			    		UserMess usermess=new UserMess();
			    		usermess.set("userid", order.get("userid"))
			    		.set("from", order.get("orderNum"))
			    		.set("title", "订单已过期")
			    		.set("des", "您好，您的订单号为:"+order.get("orderNum")+"的订单，未在有效期到店内"
			    				+ "兑换，OK妈咪已为您自动处理。")
			    		.set("state", 1).set("type", 1)
			    		.set("createDate",times)
			    		.save();

		    			//订单到期提醒消息推送 
			    		log.error(order.getInt("userid")+"-------------订单到期提醒消息推送 --------------");
		    			    User user= userservice.findByUserid(order.getInt("userid"));
							//跳转路径
							String url= PropKit.get("constants.url_prev")+"/order/detail/"+order.get("orderNum");
							String firstDATA="您在会员中心购买的"+order.get("goodsName")+"即将过期，请及时到店兑换";	
							String keyword1DATA=order.get("orderNum");
							Timestamp startDate = order.get("startDate");
							String keyword2DATA=startDate.toString();
							Timestamp expireDate = order.get("expireDate");
							String keyword3DATA=expireDate.toString();

							String remarkDATA="如有疑问请联系门店";
			
							String inviteOpenid =user.getStr("openid");
							
							Map<String,Object> map2 = new HashMap<String,Object>();
							map2.put("OPENID", inviteOpenid);
							map2.put("firstDATA", firstDATA);
							map2.put("keyword1DATA", keyword1DATA);
							map2.put("keyword2DATA", keyword2DATA);
							map2.put("keyword3DATA", keyword3DATA);
							map2.put("remarkDATA", remarkDATA);
							map2.put("url", url);
							log.error(order+"-------------订单到期提醒消息推送 --------------"+map2);
							try {
								System.out.println("订单到期提醒消息推送");

								OrderExpireApi.editWX_opinion(map2);
							} catch (SaveException e) {
								System.out.println("订单到期提醒推送失败");
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
			    		
			    		
			    	}
			    }
			    //过期退款
			    List<Order> listt=orderService.findOrderListt(times);
			    if(listt.size()>0){
			    	for (Order order : listt) {
			    			zRefunds(order.get("orderNum"));
			    	}
			    }
			    //3天未兑换订单过期
			    List<Order> lista=orderService.findOrderLista(times);
			    if(lista.size()>0){
			    	for (Order order : lista) {
			    			//发送消息
			    			UserMess usermess=new UserMess();
			    			usermess.set("userid", order.get("userid"))
			    			.set("title", "订单过期提醒")
			    			.set("from", order.get("orderNum"))
			    			.set("des", "您好，您的订单号为:"+order.get("orderNum")+"的订单，兑换期仅剩3天。"
			    					+ "请及时到店兑换。")
			    			.set("state", 1).set("type", 1)
			    			.set("createDate",times)
			    			.save();
							
			    			
			    			//订单到期提醒消息推送 
			    			    User user= userservice.findByUserid(order.getInt("userid"));
							
								//跳转路径
								String url= PropKit.get("constants.url_prev")+"/order/detail/"+order.get("orderNum");
								String firstDATA="您在会员中心购买的"+order.get("goodsName")+"即将过期，请及时到店兑换";					
								String keyword1DATA=order.get("orderNum");
								String keyword2DATA=order.get("startDate");
								String keyword3DATA=order.get("expireDate");

								String remarkDATA="如有疑问请联系门店";
				
								String inviteOpenid =user.getStr("openid");

								Map<String,Object> map2 = new HashMap<String,Object>();
								map2.put("OPENID", inviteOpenid);
								map2.put("firstDATA", firstDATA);
								map2.put("keyword1DATA", keyword1DATA);
								map2.put("keyword2DATA", keyword2DATA);
								map2.put("keyword3DATA", keyword3DATA);
								map2.put("remarkDATA", remarkDATA);
								map2.put("url", url);

								try {
									System.out.println("订单到期提醒消息推送");

									OrderExpireApi.editWX_opinion(map2);
								} catch (SaveException e) {
									System.out.println("订单到期提醒推送失败");
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
			    	}
			    }
			  } catch (Exception e) {
			   log.error("-------------解析信息发生异常--------------");
			  }
			 }
	/**
	 * 自动退款
	 */
	public void zRefunds(String orderNum){
			Order order = orderService.getOrderByOrderNums(orderNum);
			//服务类商品的兑换时间为后台设置的时间
			Order goodsType=orderService.getGoodsType(orderNum);
			String  goodtypes=""+goodsType.getInt("goodtype");    //1实物 2服务
			String  type=""+goodsType.getInt("type");    //支付方式：1：货币；2：积分;3:货币积分
			if (order != null){
				Goods goods =goodsService.getGoodById(order.getInt("goodsid"));
				long paytime = order.getDate("payDate").getTime();
				long guotime = order.getDate("guoDate").getTime();
				//实物类,纯积分服务类，以及现金服务但过期时间在七天内的   才可以自动退款（包含现金消费的服务类商品超过七天不能自动退款）
				if (goodtypes.equals("1") || (goodtypes.equals("2") && (type.equals("2"))) || (goodtypes.equals("2") && (guotime-paytime<PropKit.getLong("constants.order.intervals"))   )  ) {
				order.set("tuistate",OrderCode.RefundState.REFUNDED );
				int goodtype=goods.getInt("goodtype");
				if(order.update()){
					int userid=order.getInt("userid");
					double amount=order.getDouble("amount");
					int payPoint=order.getInt("payPoint");
					int pointType=order.getInt("pointType");
					int sppoint=order.getInt("sppoint");
					int jypoint=order.getInt("jypoint");
					int jkpoint=order.getInt("jkpoint");
					User user= userservice.findByUserid(userid);
					/*货币变更*/
					UserMoney userMoney=new UserMoney();
					/*积分变更*/
					UserValueLog userValue=new UserValueLog();
					UserValueLog userValue2=new UserValueLog();
					/*消息通知*/
					UserMess userMess=new UserMess();
					/*退款日志*/
					OrderRefund orderRefund=new OrderRefund();
					if(amount>0){
						//微信支付(微信钱包或银行卡)
						if(order.getInt("paytype")==0){
							//1------------------------先退钱
						/*	if(guotime-paytime<=PropKit.getLong("constants.order.intervals")&& (pointType!=2||pointType!=3)){
								暂时不用   
							}*/
								String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
								String refundNum = "TK"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(2);
								Map<String, String> params = new HashMap<String, String>();
								params.put("appid", PropKit.get("wx.pay.appId"));
								params.put("mch_id", PropKit.get("wx.pay.mch_id"));
								params.put("out_trade_no", orderNum);
								params.put("out_refund_no",refundNum);
								params.put("total_fee", amountStr);//总金额单位为分
								params.put("refund_fee", amountStr);//退款金额单位为分
								params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
								params.put("sign", PaymentKit.createSign(params, PropKit.get("wx.pay.key")));
								//申请退款
								Map<String, String> result=new HashMap<String, String>();
								String paternerKey=PropKit.get("wx.pay.key");
								String certPath=PathKit.getRootClassPath()+"/"+PropKit.get("wx.cert");
								result = PaymentApi.refund(params, paternerKey, certPath);
								//保存接口请求和响应内容日志
								new OrderRefundAPIRecord().set("refundNum", refundNum)
									.set("orderNum", orderNum)
									.set("payMethod", 1)
									.set("flag", 1)
									.set("sendContent", params.toString())
									.set("returnContent", PaymentKit.toXml(result))
									.save();
								orderRefund.set("refundNum", refundNum)
										   .set("type", 2)
										   .set("orderNum", orderNum)
										   .set("amount",amount)
										   .set("state", 4)
										   .save();
								userValue2.set("userid", userid).set("type", 2).set("describe", "订单退款")
								.set("storeid", order.get("storeid"))
								.set("goodsName", order.get("goodsName"))
								.set("fromOrderNum", orderNum).set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
							//2--------------------------再退积分
							if(payPoint>0){
								userValue.set("userid", userid).set("type", 1).set("describe", "订单退款")
								.set("storeid", order.get("storeid"))
								.set("goodsName", order.get("goodsName"))
								.set("fromOrderNum", orderNum).set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
									if(pointType==1){
										user.set("sppoint", user.getInt("sppoint")+payPoint-sppoint);
										user.set("jkpoint", user.getInt("jkpoint")-jkpoint);
										user.set("jypoint", user.getInt("jypoint")-jypoint);
										userValue.set("sppoint", payPoint).save();
										userValue2.set("sppoint", sppoint);
										userValue2.set("jkpoint", jkpoint);
										userValue2.set("jypoint", jypoint).save();
									}else if(pointType==2){
										user.set("jkpoint", user.getInt("jkpoint")+payPoint-jkpoint);
										user.set("sppoint", user.getInt("sppoint")-sppoint);
										user.set("jypoint", user.getInt("jypoint")-jypoint);
										userValue.set("jkpoint", payPoint).save();
										userValue2.set("sppoint", sppoint);
										userValue2.set("jkpoint", jkpoint);
										userValue2.set("jypoint", jypoint).save();
									}else if(pointType==3){
										user.set("jypoint", user.getInt("jypoint")+payPoint-jypoint);
										user.set("sppoint", user.getInt("sppoint")-sppoint);
										user.set("jkpoint", user.getInt("jkpoint")-jkpoint);
										userValue.set("jypoint", payPoint).save();
										userValue2.set("sppoint", sppoint);
										userValue2.set("jkpoint", jkpoint);
										userValue2.set("jypoint", jypoint).save();
									}
								}else{//纯货币(微信或银行卡)
									if(goodtype==1){
										user.set("sppoint", user.getInt("sppoint")-sppoint);
										user.set("jkpoint", user.getInt("jkpoint")-jkpoint);
										user.set("jypoint", user.getInt("jypoint")-jypoint);
										userValue2.set("sppoint", sppoint);
										userValue2.set("jkpoint", jkpoint);
										userValue2.set("jypoint", jypoint).save();
									}
									
								}
								user.update();
						//商城钱包支付
						}else{
						user.set("money", user.getDouble("money")+amount);
						userValue2.set("userid", userid).set("type", 2).set("describe", "订单退款")
						.set("storeid", order.get("storeid"))
						.set("goodsName", order.get("goodsName"))
						.set("fromOrderNum", orderNum).set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
						//货币积分商品
						if(payPoint>0){
							userValue.set("userid", userid).set("type", 1).set("describe", "订单退款")
							.set("storeid", order.get("storeid"))
							.set("goodsName", order.get("goodsName"))
							.set("fromOrderNum", orderNum).set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"));
								if(pointType==1){
									user.set("sppoint", user.getInt("sppoint")+payPoint-sppoint);
									user.set("jkpoint", user.getInt("jkpoint")-jkpoint);
									user.set("jypoint", user.getInt("jypoint")-jypoint);
									userValue.set("sppoint", payPoint).save();
									userValue2.set("sppoint", sppoint);
									userValue2.set("jkpoint", jkpoint);
									userValue2.set("jypoint", jypoint).save();
								}else if(pointType==2){
									user.set("jkpoint", user.getInt("jkpoint")+payPoint-jkpoint);
									user.set("sppoint", user.getInt("sppoint")-sppoint);
									user.set("jypoint", user.getInt("jypoint")-jypoint);
									userValue.set("jkpoint", payPoint).save();
									userValue2.set("sppoint", sppoint);
									userValue2.set("jkpoint", jkpoint);
									userValue2.set("jypoint", jypoint).save();
								}else if(pointType==3){
									user.set("jypoint", user.getInt("jypoint")+payPoint-jypoint);
									user.set("sppoint", user.getInt("sppoint")-sppoint);
									user.set("jkpoint", user.getInt("jkpoint")-jkpoint);
									userValue.set("jypoint", payPoint).save();
									userValue2.set("sppoint", sppoint);
									userValue2.set("jkpoint", jkpoint);
									userValue2.set("jypoint", jypoint).save();
								}
								//纯商城钱包
							}else{
								if(goodtype==1){
									user.set("sppoint", user.getInt("sppoint")-sppoint);
									user.set("jkpoint", user.getInt("jkpoint")-jkpoint);
									user.set("jypoint", user.getInt("jypoint")-jypoint);
									userValue2.set("sppoint", sppoint);
									userValue2.set("jkpoint", jkpoint);
									userValue2.set("jypoint", jypoint).save();
								}
							}
							user.update();

							userMoney.set("userid", userid).set("amount", amount)
							.set("type", 1).set("describe", "来自订单："+orderNum+"的退款已放入您的钱包余额")
							.set("fromOrderNum", orderNum).set("orderType", 1)
							.set("storeid", order.get("storeid"))
							.set("nowAmount", user.getDouble("money"))
							.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
						  }
						//纯积分商品
						}else{
							userValue.set("userid", userid).set("type", 1).set("describe", "订单退款")
							.set("storeid", order.get("storeid"))
							.set("goodsName", order.get("goodsName"));
							if(payPoint>0){
								if(pointType==1){
									user.set("sppoint", user.getInt("sppoint")+payPoint);
									 userValue.set("sppoint", payPoint).save();
								}else if(pointType==2){
									user.set("jkpoint", user.getInt("jkpoint")+payPoint);
									userValue.set("jkpoint", payPoint).save();
								}else if(pointType==3){
									user.set("jypoint", user.getInt("jypoint")+payPoint);
									userValue.set("jypoint", payPoint).save();
								}
							}
							user.update();
						}

					userMess.set("userid", userid).set("title", "退款成功").set("from", orderNum).set("des", "订单："+orderNum+"积分及货币已退还到您的账户").set("state", 1)
					.set("type", 1).set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss")).save();
 
				
					// 计算订单总积分
				/*	User user = userservice.findByUserid(getCurrentWxUserid());*/
					int pointsell = order.get("payPoint");
					/*int pointType = order.getInt("pointType");*/
				/*	String point = "";*/
					//积分变化前的积分
					/*int sppoi = user.getInt("sppoint");
					int jkpoi = user.getInt("jkpoint");
					int jypoi = user.getInt("jypoint");*/
					String pointTitle="";//积分类型名称
					if (pointType == 1 && pointsell!=0) {
						/*point = user.getInt("sppoint")+"";*/
						pointTitle="商品积分:";
					} else if (pointType == 2 && pointsell!=0) {
						/*point = user.getInt("jkpoint")+"";*/
						pointTitle="健康积分:";
					} else if (pointType == 3 && pointsell!=0) {
						/*point = user.getInt("jypoint")+"";*/
						pointTitle="教育积分:";
					}else{
						/*point="";*/
						pointTitle="";
					}
					
				
					//积分变化发送消息
					//跳转路径
					String url= PropKit.get("constants.url_prev")+"/order/detail/"+orderNum;
					String firstDATA="您在会员中心购买的"+order.get("goodsName")+"商品已退款成功";					
					String reasonDATA="订单已过兑换有效期";

					String  refundDATA="";
					
					if(!order.get("amount").equals(0.0)&&!order.get("payPoint").equals(0) ){
						refundDATA="现金"+order.get("amount")+"元,"+pointTitle+order.get("payPoint");
					}else if(order.get("amount").equals(0.0)){
						refundDATA=pointTitle+order.get("payPoint");
					}else{
						refundDATA="现金"+order.get("amount")+"元";
					}
					
					String remarkDATA="如有疑问请联系客服";
	
					String inviteOpenid =user.getStr("openid");

					Map<String,Object> map2 = new HashMap<String,Object>();
					map2.put("OPENID", inviteOpenid);
					map2.put("firstDATA", firstDATA);
					map2.put("reasonDATA", reasonDATA);
					map2.put("refundDATA", refundDATA);
					map2.put("remarkDATA", remarkDATA);
					map2.put("url", url);

					try {
						System.out.println("自动退款消息推送");

						OrderRefundApi.editWX_opinion(map2);
					} catch (SaveException e) {
						System.out.println("购买消息推送失败");
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
	   }//end if all
	}

	
   }
